#include "head.h"

int sem_init(void)
{
	int semid;
	key_t key;
	union semun myun;
	myun.val = 1;
	key = ftok("/app", 'c');
	if((semid = semget(key, 1, IPC_CREAT|IPC_EXCL|0666)) == -1)
	{
		if(errno == EEXIST)
		{
			semid = semget(key, 1, 0666);
		}else
		{
			perror("fail to semget");
			exit(1);
		}
	}
	myun.val = 1;
	if(semctl(semid, 0, SETVAL, myun) < 0)
	{
		perror("fail to semctl");
		exit(1);
	}
	return semid;
}
void sem_p(int semid)
{
	struct sembuf mybuf;
	mybuf.sem_num = 0;
	mybuf.sem_op = -1;
	mybuf.sem_flg = SEM_UNDO;
	if(semop(semid, &mybuf, 1) < 0)
	{
		perror("fail to semop");
		exit(1);
	}
}
void sem_v(int semid)
{	
	struct sembuf mybuf;
	mybuf.sem_num = 0;
	mybuf.sem_op = 1;
	mybuf.sem_flg = SEM_UNDO;
	if(semop(semid, &mybuf, 1) < 0)
	{
		perror("fail to semop");
		exit(1);
	}
}
